<template>
	<view class="container">
		<!-- 可提现金额展示 -->
		<view class="balance-card">
			<view class="balance-info">
				<text class="balance-label">可提现金额</text>
				<text class="balance-amount">¥{{ userInfo.balance || '0.00' }}</text>
			</view>
			<view class="daily-limit-info">
				<view class="limit-item">
					<text class="limit-label">今日已提现：</text>
					<text class="limit-value">¥{{ todayWithdrawTotal }}</text>
				</view>
				<view class="limit-item">
					<text class="limit-label">今日剩余额度：</text>
					<text class="limit-value">¥{{ remainingDailyAmount }}</text>
				</view>
			</view>
		</view>

		<!-- 提现操作区域 -->
		<view class="withdraw-section">
			<view class="section-title">提现申请</view>
			<view class="withdraw-form">
				<view class="form-item">
					<text class="form-label">提现金额</text>
					<view class="input-wrapper">
						<input
							class="withdraw-input"
							type="number"
							placeholder="请输入提现金额"
							v-model="withdrawAmount"
							@input="onAmountInput"
						/>
						<text class="currency">元</text>
					</view>
				</view>
				<view class="amount-tips">
					<text class="tip-text">最小提现金额：0.1元</text>
					<text class="tip-text">每日提现限额：2000元</text>
				</view>
				<view class="quick-amount">
					<text class="quick-label">快捷金额：</text>
					<view class="quick-buttons">
												<text
							class="quick-btn"
							v-for="amount in quickAmounts"
							:key="amount"
							@click="selectQuickAmount(amount)"
							:class="[withdrawAmount == amount ? 'active' : '']"
						>
							{{ amount }}元
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 提现规则 -->
		<view class="rules-section">
			<view class="section-title">提现规则</view>
			<view class="rules-content">
				<text class="rule-item">• 提现金额将在1-3个工作日内到账</text>
				<text class="rule-item">• 最小提现金额：0.1元</text>
        <text class="rule-item">• 单次最大金额：200元</text>
				<text class="rule-item">• 每日最大提现总额：2000元</text>
				<text class="rule-item">• 提现手续费：免费</text>
			</view>
		</view>

		<!-- 提现按钮 -->
		<view class="withdraw-btn-wrapper">
			<button
				class="withdraw-btn"
				:class="{ disabled: !canWithdraw }"
				:disabled="!canWithdraw"
				@click="submitWithdraw"
			>
				{{ withdrawBtnText }}
			</button>
		</view>

		<!-- 提现记录 -->
		<view class="records-section">
			<view class="section-title">提现记录</view>
			<view v-if="withdrawRecords.length > 0" class="records-list">
				<view class="record-item" v-for="record in withdrawRecords" :key="record.id">
					<view class="record-left">
						<text class="record-amount">-¥{{ Math.abs(record.amount) }}</text>
						<text class="record-time">{{ record.create_time }}</text>
					</view>
					<view class="record-right">
						<text class="record-status" :class="[getStatusClass(record.status)]">
							{{ getStatusText(record.status) }}
						</text>
					</view>
				</view>
			</view>
			<view v-else class="empty-records">
				<u-empty text="暂无提现记录" mode="data"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
	data() {
		return {
			withdrawAmount: '',
			quickAmounts: [10, 50, 100, 200],
			withdrawRecords: [],
			loading: false,
			pageNo: 1,
			pageSize: 10,
			hasMore: true,
			todayWithdrawTotal: 0, // 当日已提现总金额
			dailyLimit: 2000 // 每日提现限额
		}
	},
	computed: {
		...mapGetters(['userInfo']),

				// 是否可以提现
		canWithdraw() {
			if (!this.withdrawAmount) return false
			const amount = parseFloat(this.withdrawAmount)
			if (isNaN(amount)) return false
			if (amount < 0.1) return false
			if (amount > parseFloat(this.userInfo.balance || 0)) return false
			if (this.todayWithdrawTotal + amount > this.dailyLimit) return false
			return true
		},

		// 提现按钮文本
		withdrawBtnText() {
			if (!this.withdrawAmount) return '请输入提现金额'
			const amount = parseFloat(this.withdrawAmount)
			if (isNaN(amount)) return '请输入有效金额'
			if (amount < 0.1) return '最小提现金额0.1元'
			if (amount > parseFloat(this.userInfo.balance || 0)) return '余额不足'
			if (this.todayWithdrawTotal + amount > this.dailyLimit) return `今日提现额度不足`
			return `提现 ¥${amount}`
		},

		// 今日剩余可提现金额
		remainingDailyAmount() {
			return Math.max(0, this.dailyLimit - this.todayWithdrawTotal)
		}
	},

	onLoad() {
		this.getWithdrawRecords()
		this.getTodayWithdrawTotal()
	},

	// 下拉刷新
	onPullDownRefresh() {
		this.pageNo = 1
		this.hasMore = true
		Promise.all([
			this.getWithdrawRecords(),
			this.getTodayWithdrawTotal()
		]).then(() => {
			uni.stopPullDownRefresh()
		})
	},

	// 上拉加载更多
	onReachBottom() {
		if (this.hasMore && !this.loading) {
			this.pageNo++
			this.getWithdrawRecords()
		}
	},

	methods: {
		// 输入金额处理
		onAmountInput(e) {
			let value = e.detail.value
			// 限制最多两位小数
			if (value.includes('.')) {
				const parts = value.split('.')
				if (parts[1] && parts[1].length > 2) {
					value = parts[0] + '.' + parts[1].substring(0, 2)
				}
			}
			this.withdrawAmount = value
		},

		// 选择快捷金额
		selectQuickAmount(amount) {
			this.withdrawAmount = amount.toString()
		},

		// 选择全部金额
		selectAllAmount() {
			const balance = parseFloat(this.userInfo.balance || 0)
			const remainingAmount = this.remainingDailyAmount
			// 取余额和剩余额度中的较小值
			this.withdrawAmount = Math.min(balance, remainingAmount).toFixed(2)
		},

				// 提交提现
		async submitWithdraw() {
			if (!this.canWithdraw) return

			const amount = parseFloat(this.withdrawAmount)

			try {
				uni.showLoading({ title: '提交中...' })

				// 调用提现接口
				const res = await this.$api.createWithdraw({
					amount: amount,
					user_id: this.userInfo.id
				})

				uni.hideLoading()

				// 检查是否支持小程序提现确认功能
				if (wx.canIUse('requestMerchantTransfer')) {
					// 检查返回数据中是否包含必要字段
					if (!res.package) {
						console.warn('提现接口返回数据缺少package字段:', res);
						uni.showToast({
							title: '提现申请已提交',
							icon: 'success'
						})
						this.handleWithdrawSuccess()
						return
					}

					// 唤醒小程序提现确认
					wx.requestMerchantTransfer({
						mchId: res.mchId, // 使用后端返回的商户号
						appId: res.appId || wx.getAccountInfoSync().miniProgram.appId, // 使用后端返回的appId
						package: res.package, // 使用后端返回的package
						success: (transferRes) => {
							// 提现确认成功
							console.log('提现确认成功:', transferRes);
							uni.showToast({
								title: '提现申请已提交',
								icon: 'success'
							})
							this.handleWithdrawSuccess()
						},
						fail: (transferRes) => {
							console.log('提现确认失败:', transferRes);
							// 即使确认失败，提现申请也已提交到微信
							uni.showToast({
								title: '提现申请失败',
								icon: 'success'
							})
						}
					});
				} else {
					// 微信版本过低
					wx.showModal({
						content: '你的微信版本过低，请更新至最新版本后再尝试提现。',
						showCancel: false,
						success: () => {
							// 即使版本过低，提现申请也已提交，显示成功
							uni.showToast({
								title: '提现申请已提交',
								icon: 'success'
							})
							this.handleWithdrawSuccess()
						}
					});
				}

			} catch (error) {
				uni.hideLoading()
				uni.showToast({
					title: error.message || '提现申请失败',
					icon: 'none'
				})
			}
				},

		// 处理提现成功
		handleWithdrawSuccess() {
			// 清空输入
			this.withdrawAmount = ''

			// 刷新提现记录和用户信息
			this.getWithdrawRecords()
			this.getTodayWithdrawTotal()
			this.$store.dispatch('getUserInfo')
		},

		// 获取今日提现总金额
		async getTodayWithdrawTotal() {
			try {
				const today = new Date()
				const startDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`

				const res = await this.$api.getTodayWithdrawTotal({
					user_id: this.userInfo.id,
					date: startDate
				})

				this.todayWithdrawTotal = res.total || 0

			} catch (error) {
				console.error('获取今日提现总金额失败:', error)
				this.todayWithdrawTotal = 0
			}
		},

		// 获取提现记录
		async getWithdrawRecords() {
			if (this.loading) return
			this.loading = true

			try {
				const res = await this.$api.getBalanceRecordList({
					user_id: this.userInfo.id,
					type: 1 // 1表示提现
				})
        this.withdrawRecords = res || []
				this.hasMore = false

			} catch (error) {
				console.error('获取提现记录失败:', error)
				uni.showToast({
					title: '获取提现记录失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 获取状态样式类
		getStatusClass(status) {
			// 根据实际业务状态返回对应样式
			// 这里假设状态：1-处理中，2-已完成，3-已拒绝
			switch (status) {
				case 1: return 'status-pending'
				case 2: return 'status-success'
				case 3: return 'status-failed'
				default: return 'status-pending'
			}
		},

		// 获取状态文本
		getStatusText(status) {
			switch (status) {
				case 1: return '处理中'
				case 2: return '已完成'
				case 3: return '已拒绝'
				default: return '处理中'
			}
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background: #F8F9FA;
  height: 100%;
  overflow: hidden;
}

.container {
  height: 100%;
	padding: 20rpx;
	padding-bottom: 140rpx;
}

.balance-card {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;

	.balance-info {
		text-align: center;
		color: white;
		margin-bottom: 30rpx;

		.balance-label {
			font-size: 28rpx;
			display: block;
			margin-bottom: 10rpx;
			opacity: 0.9;
		}

		.balance-amount {
			font-size: 48rpx;
			font-weight: bold;
			display: block;
		}
	}

	.daily-limit-info {
		display: flex;
		justify-content: space-between;
		color: white;

		.limit-item {
			flex: 1;
			text-align: center;

			.limit-label {
				font-size: 24rpx;
				opacity: 0.8;
				display: block;
				margin-bottom: 8rpx;
			}

			.limit-value {
				font-size: 32rpx;
				font-weight: bold;
				display: block;
			}
		}
	}
}

.withdraw-section,
.rules-section,
.records-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
	}
}

.withdraw-form {
	.form-item {
		margin-bottom: 30rpx;

		.form-label {
			font-size: 28rpx;
			color: #666;
			display: block;
			margin-bottom: 15rpx;
		}

		.input-wrapper {
			display: flex;
			align-items: center;
			border: 2rpx solid #E5E5E5;
			border-radius: 12rpx;
			padding: 20rpx;

			.withdraw-input {
				flex: 1;
				font-size: 32rpx;
				color: #333;
			}

			.currency {
				color: #999;
				font-size: 28rpx;
				margin-left: 10rpx;
			}
		}
	}

	.amount-tips {
		margin-bottom: 30rpx;

		.tip-text {
			display: block;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 8rpx;
		}
	}

	.quick-amount {
		.quick-label {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 15rpx;
			display: block;
		}

		.quick-buttons {
			display: flex;
			flex-wrap: wrap;
			gap: 15rpx;

			.quick-btn {
				padding: 15rpx 25rpx;
				background: #F5F5F5;
				border-radius: 25rpx;
				font-size: 26rpx;
				color: #666;

				&.active {
					background: #667eea;
					color: white;
				}
			}
		}
	}
}

.rules-content {
	.rule-item {
		display: block;
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 12rpx;
	}
}

.withdraw-btn-wrapper {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx;
	background: white;
	border-top: 1rpx solid #E5E5E5;

	.withdraw-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 44rpx;
		color: white;
		font-size: 32rpx;
		font-weight: bold;
		border: none;

		&.disabled {
			background: #E5E5E5;
			color: #999;
		}
	}
}

.records-list {
	.record-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1rpx solid #F0F0F0;

		&:last-child {
			border-bottom: none;
		}

		.record-left {
			.record-amount {
				font-size: 32rpx;
				font-weight: bold;
				color: #FF6B6B;
				display: block;
				margin-bottom: 8rpx;
			}

			.record-time {
				font-size: 24rpx;
				color: #999;
			}
		}

		.record-right {
			.record-status {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 24rpx;

				&.status-pending {
					background: #FFF2E8;
					color: #FF8F00;
				}

				&.status-success {
					background: #E8F5E8;
					color: #4CAF50;
				}

				&.status-failed {
					background: #FFE8E8;
					color: #F44336;
				}
			}
		}
	}
}

.empty-records {
	padding: 60rpx 0;
}
</style>
